package com.internet;

import java.io.InputStream;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import com.essential.R;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class StationPickerActivity extends ListActivity {
	List<StationData> stationListVector = new ArrayList<StationData>();
	SAXParser parser = null;
	XMLReader reader = null;
	XMLContentHandler handler = new XMLContentHandler();
	ArrayAdapter<StationData> adapter;
	Handler handler_ui;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		handler_ui = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				setListAdapter(adapter);
			}

		};

		try {
			SAXParserFactory f = SAXParserFactory.newInstance();
			parser = f.newSAXParser();
			reader = parser.getXMLReader();
			reader.setContentHandler(handler);
			setContentView(R.layout.station);
			initList();
		} catch (Exception e) {
			Log.e("StationPicker", "Parser Fail");
			e.printStackTrace();
		}
	}

	protected void onStart() {
		super.onStart();

		Thread t = new Thread() {
			public void run() {
				HttpUriRequest request = null;
				HttpResponse resp = null;
				InputStream is = null;

				DefaultHttpClient client = new DefaultHttpClient();

				try {
					request = new HttpGet(
							"http://www.wanderingoak.net/stations.xml");
					/*
					 * HttpGet will set the Accept-Encoding as gzip mode in
					 * default. We don't need this feature.
					 */
					Header[] h = request.getHeaders("Accept-Encoding");
					if (h.length > 0) {
						request.setHeader("Accept-Encoding", "");
					}
					resp = client.execute(request);
					HttpEntity entity = resp.getEntity();
					is = entity.getContent();
					InputSource ins = new InputSource(is);
					reader.parse(ins);
				} catch (Exception e) {
					Log.e(this.getClass().getName(), "Failure");
					e.printStackTrace();
				}
			}
		};
		t.start();
	}

	class StationData {
		private String title;
		private String url;

		public StationData() {
			this.title = "No Title";
			this.url = "No URL";
		}

		public StationData(String title, String url) {
			this.title = title;
			this.url = url;
		}

		public String getTitle() {
			return title;
		}

		public void setTitle(String title) {
			this.title = title;
		}

		public String getUrl() {
			return url;
		}

		public void setUrl(String url) {
			this.url = url;
		}
	}

	class RadioArrayAdapter extends ArrayAdapter<StationData> {

		private final List<StationData> list;
		private final Activity context;

		public RadioArrayAdapter(Activity context, List<StationData> list) {
			super(context, R.layout.list_radio, list);
			this.context = context;
			this.list = list;
		}

		class ViewHolder {
			protected TextView title;
			protected TextView url;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = null;
			if (convertView == null) {
				LayoutInflater inflater = context.getLayoutInflater();
				view = inflater.inflate(R.layout.list_radio, null);
				ViewHolder vh = new ViewHolder();
				vh.title = (TextView) view
						.findViewById(R.id.res_layout_list_radio_title);
				vh.url = (TextView) view
						.findViewById(R.id.res_layout_list_radio_content);
				view.setTag(vh);
			} else {
				view = convertView;
			}
			ViewHolder vh2 = (ViewHolder) view.getTag();
			vh2.title.setText(list.get(position).getTitle());
			vh2.url.setText(list.get(position).getUrl());
			return view;
		}

	}

	private void initList() {
		adapter = new RadioArrayAdapter(this, stationListVector);
		setListAdapter(adapter);
	}

	/**
	 * 
	 * @author Bennis
	 * 
	 *         <?xml version="1.0"?> <xml> <stationList> <station>
	 *         <title>XTCRadio</title>
	 *         <audioUrl>http://206.19.69.69:443/</audioUrl> </station>
	 *         <station> <title>Pop Rock Top 40</title> <audioUrl>http://scfire
	 *         -nyk-aa02.stream.aol.com:80/stream/1074</audioUrl> </station>
	 *         <station> <title>Groove Salad</title>
	 *         <audioUrl>http://scfire-dll-aa02
	 *         .stream.aol.com:80/stream/1018</audioUrl> </station> <station>
	 *         <title>Pop Rock Top 40</title>
	 *         <audioUrl>http://scfire-chi-aa05.stream
	 *         .aol.com:80/stream/1006</audioUrl> </station> </stationList>
	 *         </xml>
	 * 
	 */
	class XMLContentHandler extends DefaultHandler {

		String taglib;
		String tag_title;
		String tag_audioUrl;

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			super.characters(ch, start, length);

			if (taglib.equals("title")) {
				tag_title = new String(ch, start, length);
			} else if (taglib.equals("audioUrl")) {
				tag_audioUrl = new String(ch, start, length);
				stationListVector.add(new StationData(tag_title, tag_audioUrl));
			}
		}

		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
			handler_ui.sendMessage(handler_ui.obtainMessage());

			StackTraceElement[] stacks = new Throwable().getStackTrace();
			Log.v(this.getClass().getName(),
					"Current Method: " + stacks[0].getMethodName()
							+ "; Invoke Method: " + stacks[1].getMethodName()
							+ "; Line: " + stacks[1].getLineNumber());
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			super.endElement(uri, localName, qName);

			taglib = "";
			if (localName.equals("station")) {
				this.debug();
			}
		}

		@Override
		public void startDocument() throws SAXException {
			super.startDocument();

			StackTraceElement[] stacks = new Throwable().getStackTrace();
			Log.v(this.getClass().getName(),
					"Current Method: " + stacks[0].getMethodName()
							+ "; Invoke Method: " + stacks[1].getMethodName()
							+ "; Line: " + stacks[1].getLineNumber());
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);

			taglib = localName;
			if (localName.equals("station")) {
				for (int i = 0; i < attributes.getLength(); i++) {
					Log.e(this.getClass().getName(), attributes.getLocalName(i)
							+ "=" + attributes.getValue(i));
				}
			}
		}

		private void debug() {
			Log.e(this.getClass().getName(), "Title=\"" + tag_title + "\"");
			Log.e(this.getClass().getName(), "Audio=\"" + tag_audioUrl + "\"");
		}
	}

}
